<?php

namespace addons\qingdong\model;

use addons\qingdong\model\Product;
use addons\qingdong\model\ProductPart;
use think\Model;

/**
 *合同关联产品
 */
class ContractProduct Extends Model {
    // 表名,不含前缀
    protected $name = 'qingdong_contract_product';
	// 开启自动写入时间戳字段
	protected $autoWriteTimestamp = false;

	//产品
	public function product() {
		return $this->hasOne(Product::class, 'id', 'product_id')
            ->bind('name,img,num,unit,cost_price');
	}
	//合同
	public function contract() {
		return $this->hasOne(Contract::class, 'id', 'contract_id')->field('id,num,name');
	}

    //产品详情
    public function productinfo(){
        return $this->belongsTo(Product::class,'product_id','id')
            ->field('id,goods_id,name,type,unit,price,cost_price')->with(['goods']);
    }
    //获取产品配置
    public function getPartsAttr($value)
    {
        $value = json_decode($value, true);
        if(empty($value)){
            return $value;
        }
        $part_ids = [];
        foreach ($value as $v) {
            $part_ids[] = $v['part_id'];
        }
        $model=new ProductPart();
        $product_part = $model->where(['id' => ['in', $part_ids]])->column('name,img', 'id');
        foreach ($value as $k => $v) {
            if (isset($product_part[$v['part_id']])) {
                $v['name'] = $product_part[$v['part_id']]['name'];
                $v['img'] = cdnurl($product_part[$v['part_id']]['img'], true);
            }
            $value[$k] = $v;
        }
        return $value;
    }

    //导入
    public static function importProduct($data) {

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->insertAll($data);
        return $result;
    }

}
